/*
* jlb
*/
package com.jlb.news.ctrl;

import com.alibaba.fastjson.JSON;
import com.jlb.core.FileUpTools;
import com.jlb.core.entity.BeanRet;
import com.jlb.core.entity.Page;
import com.jlb.core.tools.ConfigUtil;
import com.jlb.core.tools.redis.RedisUtils;
import com.jlb.news.entity.News;
import com.jlb.news.service.NewsSV;
import io.swagger.annotations.*;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import springfox.documentation.annotations.ApiIgnore;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;

/**
 * 新闻公告 控制器
 *
 * @author jlb
 */
@RestController
@RequestMapping("/news")
@Slf4j
@Api(value = "新闻公告控制器", description = "新闻公告控制器")
public class NewsCtrl {
    private final static Logger logger = LoggerFactory.getLogger(NewsCtrl.class);

    @Resource
    protected RedisUtils redisUtils;

    @Resource
    private NewsSV newsSV;

    /**
     * 查询News一个详情信息
     *
     * @param id
     * @param code 编码
     * @return BeanRet
     */
    @ApiOperation(value = "查询News一个详情信息", notes = "查询News一个详情信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "", dataType = "java.lang.Long", paramType = "query"),
            @ApiImplicitParam(name = "code", value = "编码", dataType = "java.lang.String", paramType = "query")
    })
    @GetMapping(value = "/load")
    @ResponseBody
    public BeanRet load(java.lang.Long id, java.lang.String code) {
        if (id == null) {
            return null;
        }
        if (code == null) {
            return null;
        }
        News news = newsSV.load(id, code);
        log.info(JSON.toJSONString(news));
        return BeanRet.create(true, "查询成功", news);
    }


    /**
     * 根据条件id查询News一个详情信息
     *
     * @param id
     * @return BeanRet
     */
    @ApiOperation(value = "查询News一个详情信息", notes = "查询News一个详情信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "", dataType = "java.lang.Long", paramType = "path")
    })
    @GetMapping(value = "/load/id/{id}")
    @ResponseBody
    public BeanRet loadById(@PathVariable java.lang.Long id) {
        if (id == null) {
            return null;
        }
        News news = newsSV.loadById(id);
        log.info(JSON.toJSONString(news));
        return BeanRet.create(true, "查询成功", news);
    }

    /**
     * 根据条件code查询News一个详情信息
     *
     * @param code 编码
     * @return BeanRet
     */
    @ApiOperation(value = "查询News一个详情信息", notes = "查询News一个详情信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "code", value = "编码", dataType = "java.lang.String", paramType = "path")
    })
    @GetMapping(value = "/load/code/{code}")
    @ResponseBody
    public BeanRet loadByCode(@PathVariable java.lang.String code) {
        if (code == null) {
            return null;
        }
        News news = newsSV.loadByCode(code);
        log.info(JSON.toJSONString(news));
        return BeanRet.create(true, "查询成功", news);
    }


    /**
     * 查询News信息集合
     *
     * @return 分页对象
     */
    @ApiOperation(value = "查询News信息集合", notes = "查询News信息集合")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "curPage", value = "当前页", required = true, paramType = "query"),
            @ApiImplicitParam(name = "pageSize", value = "分页大小", required = true, paramType = "query"),
            @ApiImplicitParam(name = "createTimeBegin", value = "创建时间", paramType = "query"),
            @ApiImplicitParam(name = "createTimeEnd", value = "创建时间", paramType = "query"),
            @ApiImplicitParam(name = "updateTimeBegin", value = "更新时间", paramType = "query"),
            @ApiImplicitParam(name = "updateTimeEnd", value = "更新时间", paramType = "query")
    })
    @GetMapping(value = "/list")
    @ResponseBody
    public BeanRet list(@ApiIgnore News news, Integer curPage, Integer pageSize) {
        Page<News> page = new Page<News>(pageSize, curPage);
        List<News> newss = newsSV.list(news, page.genRowStart(), page.getPageSize());
        page.setVoList(newss);
        int total = newsSV.count(news);
        page.setTotalRow(total);

        return BeanRet.create(true, "查询成功", page);

    }


    /**
     * 查询News信息集合
     *
     * @return 分页对象
     */
    @ApiOperation(value = "查询News信息集合", notes = "查询News信息集合")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "curPage", value = "当前页", required = true, paramType = "query"),
            @ApiImplicitParam(name = "pageSize", value = "分页大小", required = true, paramType = "query"),
            @ApiImplicitParam(name = "id", value = "", paramType = "query"),
            @ApiImplicitParam(name = "code", value = "编码", paramType = "query")
    })
    @GetMapping(value = "/list/by")
    @ResponseBody
    public BeanRet listByPk(java.lang.Long id, java.lang.String code, Integer curPage, Integer pageSize) {
        Page<News> page = new Page<News>(pageSize, curPage);
        List<News> newss = newsSV.list(id, code, page.genRowStart(), page.getPageSize());
        page.setVoList(newss);
        int total = newsSV.count(id, code);
        page.setTotalRow(total);

        return BeanRet.create(true, "查询成功", page);
    }

    /**
     * 统计News信息数量根据主键
     *
     * @return 总条数
     */
    @ApiOperation(value = " 统计News信息数量根据主键", notes = " 统计News信息数量根据主键")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "", paramType = "query"),
            @ApiImplicitParam(name = "code", value = "编码", paramType = "query")
    })
    @GetMapping(value = "/count/by")
    @ResponseBody
    public Integer count(java.lang.Long id, java.lang.String code) {
        return newsSV.count(id, code);
    }

    /**
     * 统计News信息数量
     *
     * @return 总条数
     */
    @ApiOperation(value = "统计News信息数量", notes = "统计News信息数量")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "", paramType = "query"),
            @ApiImplicitParam(name = "code", value = "编码", paramType = "query"),
            @ApiImplicitParam(name = "title", value = "公告标题 64个汉字", paramType = "query"),
            @ApiImplicitParam(name = "summary", value = "摘要 256个汉字", paramType = "query"),
            @ApiImplicitParam(name = "state", value = "状态：草稿 Draft，已发布  released，已删除 Delete", paramType = "query"),
            @ApiImplicitParam(name = "createTime", value = "创建时间", paramType = "query"),
            @ApiImplicitParam(name = "updateTime", value = "更新时间", paramType = "query")
    })
    @GetMapping(value = "/count")
    @ResponseBody
    public Integer count(@ApiIgnore News news) {
        if (news == null) {
            return newsSV.count(new HashMap());
        } else {
            return newsSV.count(news);
        }
    }


    /**
     * 创建News
     *
     * @return BeanRet
     */
    @ApiOperation(value = "创建News", notes = "创建News")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "title", value = "公告标题 64个汉字", paramType = "query"),
            @ApiImplicitParam(name = "content", value = "公告内容", paramType = "query"),
            @ApiImplicitParam(name = "state", value = "状态：草稿 Draft，已发布  released，已删除 Delete", paramType = "query"),
            @ApiImplicitParam(name = "createTime", value = "创建时间", paramType = "query"),
            @ApiImplicitParam(name = "updateTime", value = "更新时间", paramType = "query")
    })
    @PostMapping("/build")
    @ResponseBody
    public BeanRet build(@ApiIgnore News news, String content) {
        newsSV.insert(news, content);
        return BeanRet.create(true, "创建成功", news);
    }


    /**
     * 修改News
     *
     * @return BeanRet
     */
    @ApiOperation(value = "修改News", notes = "修改News")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "", paramType = "query"),
            @ApiImplicitParam(name = "code", value = "编码", paramType = "query"),
            @ApiImplicitParam(name = "title", value = "公告标题 64个汉字", paramType = "query"),
            @ApiImplicitParam(name = "content", value = "公告内容", paramType = "query"),
            @ApiImplicitParam(name = "summary", value = "摘要 256个汉字", paramType = "query"),
            @ApiImplicitParam(name = "state", value = "状态：草稿 Draft，已发布  released，已删除 Delete", paramType = "query"),
            @ApiImplicitParam(name = "createTime", value = "创建时间", paramType = "query"),
            @ApiImplicitParam(name = "updateTime", value = "更新时间", paramType = "query")
    })
    @PutMapping("/modify")
    @ResponseBody
    public BeanRet modify(@ApiIgnore News news, String content) {
        newsSV.update(news, content);
        return BeanRet.create(true, "修改成功", news);
    }

    /**
     * 删除News
     *
     * @return BeanRet
     */
    @ApiOperation(value = "删除News", notes = "删除News")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "", paramType = "query"),
            @ApiImplicitParam(name = "code", value = "编码", paramType = "query")
    })
    @DeleteMapping("/delete")
    @ResponseBody
    public BeanRet delete(java.lang.Long id, java.lang.String code) {
        newsSV.delete(id, code);
        return BeanRet.create(true, "删除News成功");
    }


    @ApiOperation(value = "上传图片", notes = "上传图片")
    @PostMapping("/upload")
    @ResponseBody
    public void upload(HttpServletRequest request, HttpServletResponse response, @ApiParam(value = "springmvc文件对象", required = true) @RequestParam MultipartFile upload) {
        boolean result = false;
        FileUpTools fileUpTools = new FileUpTools();
        String path = ConfigUtil.getValue("upload_temp_dir", "upload_config.properties");
        String suffix = ConfigUtil.getValue("suffix_img", "upload_config.properties");
        String domain = ConfigUtil.getValue("service_domain", "upload_config.properties");
        String fileName = System.currentTimeMillis() + suffix;
        try {
            InputStream inputStream = upload.getInputStream();
            fileUpTools.uploadFileToLocal(inputStream, path, fileName);
            result = true;
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            response.setContentType("text/html;charset=UTF-8");
            String callback = request.getParameter("CKEditorFuncNum");
            PrintWriter out = response.getWriter();
            if (result) {
                out.println("<script type=\"text/javascript\">");
                out.println("window.parent.CKEDITOR.tools.callFunction(" + callback + ",'" + domain + "/" + fileName + "',''" + ")");
                out.println("</script>");
            } else {
                out.println("<script type=\"text/javascript\">");
                out.println("window.parent.CKEDITOR.tools.callFunction(" + callback + ",''," + "'上传失败');");
                out.println("</script>");
            }
            out.flush();
            out.close();
        } catch (Exception e) {
            logger.info("<< 上传失败，原因是:" + e.getMessage());
        }
    }


}
